package com.zcsy.manage.web.mall;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.model.RequestConstants;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.commons.unique.UniqueNumberUtils;
import com.zcsy.commons.util.DateUtils;
import com.zcsy.manage.model.base.CellInfo;
import com.zcsy.manage.model.base.ShopInfo;
import com.zcsy.manage.model.mall.CouponDetail;
import com.zcsy.manage.model.mall.CouponInfo;
import com.zcsy.manage.model.system.Dict;
import com.zcsy.manage.model.system.User;
import com.zcsy.manage.service.base.ICellInfoService;
import com.zcsy.manage.service.base.IShopInfoService;
import com.zcsy.manage.service.mall.ICouponDetailService;
import com.zcsy.manage.service.mall.ICouponInfoService;
import com.zcsy.manage.service.system.IDictService;
import com.zcsy.manage.web.common.LogUtils;
import com.zcsy.manage.web.tools.JExcelReport;

/**
 * 
 * @Title: CouponInfoController.java
 * @Package： com.zcsy.manage.web.mall 
 * @Description: 优惠券信息控制层
 * @author lilan 1063972142@qq.com
 * @Copyright: 2015 武汉恒数利通信息技术有限公司 All rights reserved.
 * @date 2016年6月6日
 * @version 1.0
 * @see JDK1.7.0_75
 * @since
 */
@Controller
@RequestMapping(value = "couponInfo")
public class CouponInfoController {
	
    @Autowired
    private ICouponInfoService couponInfoService;
    
    @Autowired
    private ICouponDetailService couponDetailService;
    
    @Autowired
    private ICellInfoService cellInfoService;
    
    @Autowired
    private IShopInfoService shopInfoService;

    @Autowired
    private IDictService dictService;
	
	/**新注册 */
	private static final int STATE_NEW          =  1; 
	/**正常 */
	private static final int STATE_SUCCESS      =  2;  
	/**系统禁用*/
	private static final int STAET_FORBIDEN     =  3;  
	/**商户禁用*/
	private static final int STAET_FORBID     =  5;  
	/**未通过审核 */
	private static final int STATE_UNAPPROVED   =  4;  
	/**商户*/
	private static final int TYPE_BUSINESS  =  2; 
	/**平台*/
	private static final int TYPE_PLATFORM  =  1; 
	/**优惠券初始状态*/
	private static final int COUPON_STATE  =  -1; 
	/**优惠券初始状态*/
	private static final int COUPON_STATE_SEND  =  2; 
	/**优惠券初始状态*/
	private static final int COUPON_STATE_USED  =  3; 
	
	/**
	 * 
	 * @Description 返回优惠券申请列表页面<br>
	 * 
	 * @param model
	 * @param pNo 当前页
	 * @param userAccount 发布账号
	 * @param req 用户请求
	 * @return 
	 * @author lilan 1063972142@qq.com
	 * @date 2016年4月21日
	 * @see
	 */
	@RequestMapping(value ="/couponApply", method = RequestMethod.GET)
	public String adApply(Model model, Integer pNo, Integer pSize, String userAccount,String cellId,
			String shopId, HttpServletRequest req){
		
		if (pNo == null) {
			pNo = Constants.PAGE_NO;
		}

		Integer pageSize;
		if (pSize == null) {
			pageSize = Constants.PAGE_SIZE;
		} else {
			switch (pSize) {
				case 0: pageSize = Constants.PAGE_SIZE;
				break;
				case 1: pageSize = Constants.PAGE_SIZE_TWENTY;
				break;
				case 2: pageSize = Constants.PAGE_SIZE_FIFTY;
				break;
				default:pageSize = Constants.PAGE_SIZE;
				break;
			}
		}
		
		// 此处添加PageHelper将会走拦截器，进行分页，分页方法只针对紧跟着PageHelper的查询方法有效
		PageHelper.startPage(pNo, pageSize);
		
		CouponInfo couponInfo = new CouponInfo();
		if(StringUtils.isNotEmpty(userAccount)){
			couponInfo.setUserAccount(userAccount);
		}
		if(StringUtils.isNotEmpty(cellId)){
		couponInfo.setCellId(cellId);
	    }
	    if(StringUtils.isNotEmpty(shopId)){
		couponInfo.setShopId(shopId);
	    }
	    couponInfo.setUserAccountType(TYPE_BUSINESS);
	    
		List<CouponInfo> couponInfos = couponInfoService.selectByApplyKeyword(couponInfo);
		List<CellInfo> cellInfos = cellInfoService.getAllCellInfo();
		List<ShopInfo> shopInfos = shopInfoService.getAllShopInfo();
		PageInfo<CouponInfo> info = new PageInfo<CouponInfo>(couponInfos);
		
		model.addAttribute("cellinfos", cellInfos);
		model.addAttribute("shopinfos", shopInfos);
		model.addAttribute("couponInfo", info);
		model.addAttribute("currentPage", pNo);
		model.addAttribute("pSize", pSize);
		model.addAttribute("userAccount", userAccount);

		List<Dict> pageSizes = dictService.getDictFromCache("pageSize");
		model.addAttribute("pageSizes", pageSizes);
		
		return "mall/couponinfo/couponApply";
	}
	
	
	/**
	 * 
	 * @Description 更改发布账号状态<br>
	 * 
	 * @param model
	 * @param id 主键id
	 * @param state 1新申请 2正常 3禁用 4已拒绝
	 * @return 
	 * @author lilan 1063972142@qq.com
	 * @date 2016年4月21日
	 * @see
	 */
	 @RequestMapping(value= "/couponApplyUpdate", method = RequestMethod.POST)
	 @ResponseBody
	 public RequestJson adApplyUpdate(Model model, String id, int state, HttpServletRequest request){
			 RequestJson result = new RequestJson();
			 User user = (User)request.getSession().getAttribute(RequestConstants.USER_SESSION_ID);

			 int temp = 0;
			 try {
				 CouponInfo couponInfo = new CouponInfo();
				 couponInfo.setId(id);
				 switch (state) {
				 case STATE_NEW:
					 temp = STATE_UNAPPROVED;
					 break;
				 case STATE_UNAPPROVED:
					 temp = STATE_NEW;
					 break;
				 case STATE_SUCCESS:
					 temp = STAET_FORBIDEN;
					 break;
				 case STAET_FORBIDEN:
					 temp = STATE_SUCCESS;
					 break;
				 case STAET_FORBID:
					 temp = STATE_SUCCESS;
					 break;
				 default:
					 temp = STATE_SUCCESS;
					 break;
				 }
				 couponInfo.setState(temp);
				 couponInfoService.update(couponInfo);
				 LogUtils.insertLog("用户编辑优惠券发布账号状态", user.getId(), request);

			 } catch (Exception e) {
				 result.setSuccess(false);
			 }
			 
			return result;
		}
	 
	 /**
	  * @Description 返回优惠券信息列表页面<br>
	  * @param model
	  * @param pNo 当前页
	  * @param name 优惠券名称
	  * @param cellId 小区ID
	  * @param shopId 店铺ID
	  * @param req 用户请求
	  * @author lilan 1063972142@qq.com
	  * @date 2016年4月25日
	  * @see
	  */
	 @RequestMapping(value ="/couponInfoList", method = RequestMethod.GET)
		public String couponInfoList(Model model, Integer pNo, Integer pSize, String name, Integer userAccountType, HttpServletRequest req){
			
			if (pNo == null) {
				pNo = Constants.PAGE_NO;
			}
			
			Integer pageSize;
			if (pSize == null) {
				pageSize = Constants.PAGE_SIZE;
			} else {
				switch (pSize) {
					case 0: pageSize = Constants.PAGE_SIZE;
					break;
					case 1: pageSize = Constants.PAGE_SIZE_TWENTY;
					break;
					case 2: pageSize = Constants.PAGE_SIZE_FIFTY;
					break;
					default:pageSize = Constants.PAGE_SIZE;
					break;
				}
			}
			
			// 此处添加PageHelper将会走拦截器，进行分页，分页方法只针对紧跟着PageHelper的查询方法有效
			PageHelper.startPage(pNo, pageSize);
			
			CouponInfo couponInfo = new CouponInfo();
			//获取当前小区id
//			User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
//			String cellId = user.getCurrentCell().getId();
			
			if(StringUtils.isNotEmpty(name)){
				couponInfo.setName(name);
			}
			if(null != userAccountType){
		            couponInfo.setUserAccountType(userAccountType);
		        }
			 
//			couponInfo.setCellId(cellId);
	        
			List<CouponInfo> couponInfos = couponInfoService.selectByKeyword(couponInfo);
			PageInfo<CouponInfo> info = new PageInfo<CouponInfo>(couponInfos);
//			List<CellInfo> cellInfos = cellInfoService.getAllCellInfo();
			List<ShopInfo> shopInfos = shopInfoService.getAllShopInfo();
			List<Dict> userAccountTypes = dictService.getDictFromCache("userAccountTypes");
			
//			model.addAttribute("cellinfos", cellInfos);
			model.addAttribute("shopinfos", shopInfos);
			model.addAttribute("couponInfo", info);
			model.addAttribute("currentPage", pNo);
			model.addAttribute("pSize", pSize);
			model.addAttribute("name", name);
			model.addAttribute("userAccountTypeId", userAccountType);
	        model.addAttribute("userAccountTypes", userAccountTypes);

			List<Dict> pageSizes = dictService.getDictFromCache("pageSize");
			model.addAttribute("pageSizes", pageSizes);

			return "mall/couponinfo/couponInfoList";
		}
	 
	 /**
	  * @Description 返回优惠券信息新增页面<br>
	  * @param model
	  * @param id 主键ID
	  * @author lilan 1063972142@qq.com
	  * @date 2016年4月25日
	  * @see
	  */
	 @RequestMapping(value = "editCouponInfo", method = RequestMethod.GET)
	    public String selectById(Model model, String id) {
	    	 try {
	             if (String.valueOf(Constants.STATE_DISABLED).equals(id)) {
	                 model.addAttribute("type", Constants.SAVE_TYPE);
	             } else {
	                 CouponInfo couponInfo = couponInfoService.selectByPrimaryKey(id);
	                 if(couponInfo != null){
	                	 model.addAttribute("type", Constants.EDIT_TYPE);
	                 	model.addAttribute("couponInfo", couponInfo);
	                 	model.addAttribute("cellid", couponInfo.getCellId());
	                 	model.addAttribute("shopid", couponInfo.getShopId());
	                 }
	             }
	             List<CellInfo>  cellInfos = cellInfoService.getAllCellInfo();
	             List<ShopInfo> shopInfos = shopInfoService.getAllShopInfo();
	 			model.addAttribute("cellinfos",cellInfos);
	 			model.addAttribute("shopinfos", shopInfos);
	             
	         } catch (Exception e) {
	         }
	    	 
	         return "mall/couponinfo/couponInfoEdit";
	     }
	 
	 /**
	  * @Description 保存和更新优惠券信息页面<br>
	  * @param name 优惠券名称
	  * @param id 主键ID
	  * @param type 优惠券类型 1平台新人券、2平台邀请券3满减券4商家免运费券
	  * @param cellId 小区ID
	  * @param shopId 店铺ID
	  * @param breakLine 减免线
	  * @param breakPrice 减免金额
	  * @param beginDate 开始时间
	  * @param endDate 结束时间
	  * @param count 数量
	  * @param availableDay 有效天数
	  * @param state 状态 1新申请，2正常，3禁用，4审核未通过
	  * @param userAccount 发布账号
	  * @param userAccountType 账号类型
	  * @param req 用户请求
	  * @author lilan 1063972142@qq.com
	  * @date 2016年4月25日
	  * @see
	  */
	 @RequestMapping(value="saveOrUpdateCouponInfo" , method = RequestMethod.POST)
	    @ResponseBody
	    public RequestJson saveOrUpdateCouponInfo(String name,String id,Integer type,
	            BigDecimal breakLine,BigDecimal breakPrice,String beginDate,String endDate,
	            Integer count,String useBeginDate,String useEndDate,HttpServletRequest req){
	        RequestJson result = new RequestJson();
	        User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);

	        CouponInfo couponInfo = new CouponInfo();
	        couponInfo.setName(name);
	        couponInfo.setType(type);
	        couponInfo.setBreakLine(breakLine);
	        couponInfo.setBreakPrice(breakPrice);
	        couponInfo.setBeginDate(beginDate);
	        couponInfo.setEndDate(endDate);
	        couponInfo.setCount(count);
	        couponInfo.setUseBeginDate(useBeginDate);
	        couponInfo.setUseEndDate(useEndDate);
	        couponInfo.setState(STATE_SUCCESS);
	        couponInfo.setUserAccountType(TYPE_PLATFORM);
	        couponInfo.setUserAccount(user.getLoginname());
	        couponInfo.setCellId(user.getCurrentCell().getId());
	        try {
	            if(id != ""&& !"0".equals(id)){
	                couponInfo.setId(id);
	            	couponInfoService.update(couponInfo);
	            	LogUtils.insertLog("用户编辑优惠券信息", user.getId(), req);

	            }else{
	            	couponInfo.setId(UniqueNumberUtils.get18UniqueNumber());
	            	couponInfo.setCreateTime(new Date());
	            	couponInfoService.insert(couponInfo);
	            	LogUtils.insertLog("用户新增优惠券信息", user.getId(), req);

	            }
	            result.setSuccess(true);
	        } catch (Exception e) {
	            result.setMsg("操作失败");
	        }
	        
	        return result;
	    }
	 
	 /**
		 * @Description 返回优惠券申请列表页面<br>
		 * @param pNo 当前页
		 * @param userAccount 发布账号
		 * @param req 用户请求
		 * @author lilan 1063972142@qq.com
		 * @date 2016年4月21日
		 * @see
		 */
		@RequestMapping(value ="/couponDetailList", method = RequestMethod.GET)
		public String adApply(Model model, Integer pNo, Integer pSize, String id, Integer couponstate, HttpServletRequest req){
			CouponInfo couponInfo = couponInfoService.selectByPrimaryKey(id);
            model.addAttribute("couponInfo", couponInfo);

            CouponDetail couponDetail = new CouponDetail();
			if (pNo == null) {
				pNo = Constants.PAGE_NO;
			}
			if(couponstate == null){
				couponstate = COUPON_STATE;
			}

			Integer pageSize;
			if (pSize == null) {
				pageSize = Constants.PAGE_SIZE;
			} else {
				switch (pSize) {
					case 0: pageSize = Constants.PAGE_SIZE;
					break;
					case 1: pageSize = Constants.PAGE_SIZE_TWENTY;
					break;
					case 2: pageSize = Constants.PAGE_SIZE_FIFTY;
					break;
					default:pageSize = Constants.PAGE_SIZE;
					break;
				}
			}
			
			couponDetail.setState(couponstate);
			couponDetail.setCouponId(id);
			// 此处添加PageHelper将会走拦截器，进行分页，分页方法只针对紧跟着PageHelper的查询方法有效
			PageHelper.startPage(pNo, pageSize);
			List<CouponDetail> couponDetails = couponDetailService.selectByKeyword(couponDetail);
			PageInfo<CouponDetail> info = new PageInfo<CouponDetail>(couponDetails);
			model.addAttribute("couponDetail", info);
			model.addAttribute("couponstate", couponstate);
			model.addAttribute("currentPage", pNo);
			model.addAttribute("pSize", pSize);

			List<Dict> pageSizes = dictService.getDictFromCache("pageSize");
			model.addAttribute("pageSizes", pageSizes);

			return "mall/couponinfo/couponDetail";
		}
		

	 /**
	  * @Description 根据主键id删除优惠券信息记录<br>
	  * @param ids 优惠券信息对象id数组
	  * @param req 用户请求
	  * @author lilan 1063972142@qq.com
	  * @date 2016年4月21日
	  * @see
	  */
	 @RequestMapping(value = "deleteByPrimaryKey", method = RequestMethod.POST)
	    @ResponseBody
	    public RequestJson deleteByPrimaryKey(String ids, HttpServletRequest req){
	    	RequestJson result = new RequestJson();
	    	User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);

	    	 try {
	 			String keys[] = ids.split("\\,");
	 			for (int i = 0; i < keys.length; i++ ) {
	 			   couponInfoService.deleteByPrimaryKey(keys[i]);
	 			}
	 			LogUtils.insertLog("用户删除优惠券信息", user.getId(), req);
	 			result.setSuccess(true);
	 		} catch (NumberFormatException e) {
	 	        result.setSuccess(false);
	 	        result.setMsg("操作失败");
	 		}
	    	 
	         return result;
	     }
	 
	 /**
	  * @Description 导出优惠券发放和使用清单<br>
	  * @param id 主键ID
	  * @param response 用户响应
	  * @author lilan 1063972142@qq.com
	  * @date 2016年5月4日
	  * @see
	  */
	 @RequestMapping("/exportCouponDetailExcel")
	    @ResponseBody
	    public void exportFeeBillExcel(String id,Integer couponstate, HttpServletResponse response, HttpServletRequest request) {
	        List<CouponDetail> list;
	        CouponDetail record = new CouponDetail();
	        User user = (User)request.getSession().getAttribute(RequestConstants.USER_SESSION_ID);

	        if (StringUtils.isNotEmpty(id)) {
	            record.setCouponId(id);
	        }
	        if(couponstate == null){
				couponstate = COUPON_STATE;
			}
			
	        record.setState(couponstate);
	        try {
	            //得到导出的数据列表
	            list = couponDetailService.selectByKeyword(record);
	            
	            // 将优惠券信息对象转化为到处所需要的数据格式
	            if (list.size() > 0) {
	                ArrayList<ArrayList<String>> dataList = new ArrayList<ArrayList<String>>();
	                int index =1;
	                for(CouponDetail detail : list){
	                    ArrayList<String> temp = new ArrayList<String>();
	                    //序号
	                    temp.add(String.valueOf(index++));
	                    //temp.add(detail.getId());
	                    temp.add(detail.getCouponName());
	                    temp.add(detail.getUserAccount());
	                    temp.add(detail.getCouponCode());
	                    temp.add(detail.getCode());
	                    Integer states = detail.getState();
	                    if(states == COUPON_STATE_SEND){
	                    	temp.add("已下发");
	                    }
	                    if(states == COUPON_STATE_USED){
	                    	temp.add("已使用");
	                    }
	                    temp.add(detail.getPhone());
	                    temp.add(detail.getImei());
	                    temp.add(DateUtils.formatDate(detail.getUseTime()));
	                    temp.add(DateUtils.formatDate(detail.getExpireTime()));
	                    temp.add(DateUtils.formatDate(detail.getCreateTime()));
	                    dataList.add(temp);
	                }
	                // 导出标题列
//	                String[] rows = new String[] {"序号","优惠券名称","发布账号","优惠券信息编码","优惠券详情编码",
//	                		                      "优惠券状态","电话","imei","使用时间","过期时间","创建时间"};
	                String[] rows = "序号,优惠券名称,发布账号,优惠券信息编码,优惠券详情编码,优惠券状态,电话,imei,使用时间,过期时间,创建时间".split(",");
	                // 导出excel文件每列宽度
	                int[] style = new int[] {5,20,20,20,20,20,20,20,20,20,20};
	                // Excel文件sheet名称
	                String sheetName = "优惠券"+list.get(0).getCouponName()+"发放和使用清单"+DateUtils.getCurrentDate();
	                String fileName = "优惠券"+list.get(0).getCouponName()+"发放和使用清单";
	                doExecl(response,fileName,sheetName, dataList, rows, style);
	                LogUtils.insertLog(" 导出优惠券发放和使用清单", user.getId(), request);
	            }
	        } catch(Exception e) {
	            return;
	        }
	    }
	    
	 	/**
	 	 * @Description 通过传入的对象信息集合产生的excel表格<br>
	 	 * @param response 用户响应
	 	 * @param sheetName excel表名称
	 	 * @param dataList 传入的数据列表
	 	 * @param rows excel表的列控制，名称
	 	 * @param style 规定列宽等样式
	 	 * @throws Exception 
	 	 * @author lilan 1063972142@qq.com
	 	 * @date 2016年5月4日
	 	 * @see
	 	 */
	    private void doExecl(HttpServletResponse response,String tempName, String sheetName,
	            ArrayList<ArrayList<String>> dataList, String[] rows, int[] style) throws Exception {
	        //输出的excel名称为中文，否则发生错误
	        String tempFileName = tempName+".xls";
	        String fileName = new String(tempFileName.getBytes("GB2312"), "ISO_8859_1"); 
	        
	        ServletOutputStream fout = response.getOutputStream();
	        response.setContentType("application/vnd.ms-excel");
	        response.setHeader("Content-Disposition", "filename="+fileName+"");
	        JExcelReport jexcelOutStream = new JExcelReport();
	        try {
	            jexcelOutStream.excelreport(sheetName, dataList, rows, fout, style);
	            fout.flush();
	            fout.close();
	        } catch (Exception e){
	            e.printStackTrace();
	        }
	        
	    }
}
